//
//  DetailViewController.m
//  Comic
//
//  Created by Andy.He on 16/3/14.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "DetailViewController.h"
#import "DetailTableViewCell.h"
#import "ComicModel.h"
#import "DetailComicModel.h"
#import "AuthorViewController.h"
#import "WebViewController.h"
#import "ComiContentViewController.h"

#define COMIC_SORT @"http://api.kuaikanmanhua.com/v1/topics/"

@interface DetailViewController () <UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) IBOutlet UIView *detailHeader;

@property (strong, nonatomic) IBOutlet UIButton *popBtn;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *cons_top;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *cons_bottom;
@property (strong, nonatomic) IBOutlet UIImageView *backImageView;
@property (strong, nonatomic) IBOutlet UIView *titleBackView;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;

@property (strong, nonatomic) NSMutableArray *topicDataArr;
@property (strong, nonatomic) NSMutableArray *comicListArr;

@property (strong, nonatomic) IBOutlet UITableView *comicDetailTable;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *btnLeft;
@property (strong, nonatomic) IBOutlet UIButton *introBtn;


@property (strong, nonatomic) IBOutlet NSLayoutConstraint *btnRight;
@property (strong, nonatomic) IBOutlet UIButton *contentBtn;

@property (nonatomic, strong)NSNumber *click;
@property (nonatomic, strong)NSMutableDictionary *data;
@property (nonatomic, strong)NSMutableDictionary *user;
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self headerSetting];
    [self tableSetting];
    [self btnSetting];
    [self dataJson:0];
}

- (void)btnSetting{
    self.btnLeft.constant = SCREEN_WIDTH / 2;
    self.introBtn.layer.borderWidth = 0.5;
    self.introBtn.layer.borderColor = [UIColor colorWithWhite:0.845 alpha:1.000].CGColor;
    [self.introBtn setTintColor:[UIColor darkGrayColor]];
    [self.introBtn setTitle:@"简介" forState:UIControlStateNormal];
    [self.introBtn addTarget:self action:@selector(infoText:) forControlEvents:UIControlEventTouchUpInside];
    
    self.btnRight.constant = SCREEN_WIDTH / 2;
    self.contentBtn.layer.borderWidth = 0.5;
    self.contentBtn.layer.borderColor = [UIColor colorWithWhite:0.845 alpha:1.000].CGColor;
    [self.contentBtn setTintColor:[UIColor blackColor]];
    [self.contentBtn setTitle:@"内容" forState:UIControlStateNormal];
    [self.contentBtn addTarget:self action:@selector(contentText:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)infoText:(UIButton *)btn{
    self.click = [NSNumber numberWithFloat:1];
    [self.introBtn setTintColor:[UIColor blackColor]];
    [self.contentBtn setTintColor:[UIColor darkGrayColor]];
    [self.comicDetailTable reloadData];
}

- (void)contentText:(UIButton *)btn{
    self.click = [NSNumber numberWithFloat:2];
    [self.introBtn setTintColor:[UIColor darkGrayColor]];
    [self.contentBtn setTintColor:[UIColor blackColor]];
    [self.comicDetailTable reloadData];
}

- (void)dataJson:(NSInteger)num{
    
    NSString *str;
    if (self.headerData.topic_ID != nil) {
        str = [NSString stringWithFormat:@"%@",self.headerData.topic_ID];
        NSLog(@"%@",str);
    }else if (![self.idNumber isEqualToString:@""]){
        str = [NSString stringWithFormat:@"%@",self.idNumber];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *detailURL = [NSString stringWithFormat:@"%@%@?sort=%ld",COMIC_SORT,str,num];
    [manager GET:detailURL parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.topicDataArr = [NSMutableArray array];
        self.comicListArr = [NSMutableArray array];
        self.data = [NSMutableDictionary dictionary];
        self.data = responseObject[@"data"];
        self.user = [NSMutableDictionary dictionary];
        self.user = [responseObject[@"data"]objectForKey:@"user"];
        for (NSDictionary *dic in responseObject[@"data"][@"comics"]) {
            DetailComicModel *detailComicMod = [[DetailComicModel alloc] init];
            [detailComicMod setValuesForKeysWithDictionary:dic];
            [self.comicListArr addObject:detailComicMod];
        }
//        [self.backImageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"cover_image_url"]]];
        [self.backImageView setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"cover_image_url"]] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
        self.titleLabel.text = responseObject[@"data"][@"title"];
        [self.comicDetailTable reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}

#pragma mark  颜色的渐变
- (CAGradientLayer *)shadowAsInverse
{
    CAGradientLayer *newShadow = [[CAGradientLayer alloc] init];
    CGRect newShadowFrame = self.detailHeader.frame;
    newShadow.frame = newShadowFrame;
    //添加渐变的颜色组合（颜色透明度的改变）
    newShadow.colors = [NSArray arrayWithObjects:
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0] CGColor] ,
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.1] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.2] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.3] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.4] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.5] CGColor],
                        nil];
    return newShadow;
}

- (void)headerSetting{
    self.comicDetailTable.tableHeaderView = self.detailHeader;
//    [self.titleLabel.layer addSublayer:[self shadowAsInverse]];
    self.titleLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.200];
    [self.popBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [self.popBtn addTarget:self action:@selector(popToUpper) forControlEvents:UIControlEventTouchUpInside];
    [self.popBtn setTintColor:[UIColor colorWithRed:1.000 green:0.870 blue:0.041 alpha:1.000]];
}

- (void)popToUpper{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tableSetting{
    [self.comicDetailTable registerNib:[UINib nibWithNibName:NSStringFromClass([DetailTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([DetailTableViewCell class])];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSNumber *one = [NSNumber numberWithFloat:1];
    NSNumber *two = [NSNumber numberWithFloat:2];
    if ([self.click isEqualToNumber:two]) {
        
        return self.comicListArr.count;
    }else if([self.click isEqualToNumber:one]) {
        return 2;
    }else{
    return self.comicListArr.count;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSNumber *one = [NSNumber numberWithFloat:1];
    NSNumber *two = [NSNumber numberWithFloat:2];
    if ([self.click isEqualToNumber:two]) {
    DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DetailTableViewCell class]) forIndexPath:indexPath];
    DetailComicModel *model = self.comicListArr[indexPath.row];
//    [cell.comicPic sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
    [cell.comicPic setImageWithURL:[NSURL URLWithString:model.cover_image_url] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
    cell.comicTitle.text = model.title;
    NSString *like = [NSString stringWithFormat:@"%@",model.likes_count];
        if (like.length > 5) {
            long likeCount = like.length - 4;
            NSString *likec = [like substringWithRange:NSMakeRange(0, likeCount)];
            cell.likeCount.text = [NSString stringWithFormat:@"%@万",likec];
        }else{
            cell.likeCount.text = [NSString stringWithFormat:@"%@",model.likes_count];
        }
    NSString *timeStr = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeIntervalSince1970:[model.updated_at integerValue]]];
    timeStr = [timeStr substringWithRange:NSMakeRange(5, 11)];
    cell.comicTime.text = timeStr;
    return cell;
    }else if([self.click isEqualToNumber:one]){
        static NSString *reuse = @"reuse";
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = self.data[@"description"];
            cell.textLabel.numberOfLines = 3;
            [cell.textLabel sizeToFit];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
        }else if (indexPath.row == 1){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.imageView.layer.cornerRadius = 25;
            cell.imageView.layer.masksToBounds = YES;
//            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.user[@"avatar_url"]]];
            [cell.imageView setImageWithURL:[NSURL URLWithString:self.user[@"avatar_url"]] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
            cell.textLabel.text = self.user[@"nickname"];
            cell.textLabel.font = [UIFont systemFontOfSize:18];
        }
        return cell;
    }else{
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DetailTableViewCell class]) forIndexPath:indexPath];
        DetailComicModel *model = self.comicListArr[indexPath.row];
//        [cell.comicPic sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
        [cell.comicPic setImageWithURL:[NSURL URLWithString:model.cover_image_url] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
        cell.comicTitle.text = model.title;
        cell.likeCount.text = [NSString stringWithFormat:@"%@",model.likes_count];
        NSString *like = [NSString stringWithFormat:@"%@",model.likes_count];
        if (like.length > 5) {
            long likeCount = like.length - 4;
            NSString *likec = [like substringWithRange:NSMakeRange(0, likeCount)];
            cell.likeCount.text = [NSString stringWithFormat:@"%@万",likec];
        }else{
            cell.likeCount.text = [NSString stringWithFormat:@"%@",model.likes_count];
        }
        NSString *timeStr = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeIntervalSince1970:[model.updated_at integerValue]]];
        timeStr = [timeStr substringWithRange:NSMakeRange(5, 11)];
        cell.comicTime.text = timeStr;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSNumber *one = [NSNumber numberWithFloat:1];
    NSNumber *two = [NSNumber numberWithFloat:2];
    if ([self.click isEqualToNumber:one]) {
        AuthorViewController *authVC = [[AuthorViewController alloc] init];
        authVC.authorUrl = [NSString stringWithFormat:@"%@",self.user[@"id"]];
        [self.navigationController pushViewController:authVC animated:YES];
    }else if ([self.click isEqualToNumber:two]){
        DetailComicModel *model = self.comicListArr[indexPath.row];
        ComiContentViewController *comicVC = [[ComiContentViewController alloc] init];
        comicVC.nameTitle = model.title;
        comicVC.idNUmber = [NSString stringWithFormat:@"%@",model.idNumber];
        [self.navigationController pushViewController:comicVC animated:YES];
    }else{
        DetailComicModel *model = self.comicListArr[indexPath.row];
        ComiContentViewController *comicVC = [[ComiContentViewController alloc] init];
        comicVC.nameTitle = model.title;
        comicVC.idNUmber = [NSString stringWithFormat:@"%@",model.idNumber];
        [self.navigationController pushViewController:comicVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSNumber *one = [NSNumber numberWithFloat:1];
    NSNumber *two = [NSNumber numberWithFloat:2];
    if ([self.click isEqualToNumber:two]) {
        
        return 110;
    }else if ([self.click isEqualToNumber:one]){
        return 50;
    }else{
    return 110;
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.cons_top.constant = 250 - scrollView.contentOffset.y;
    if (self.cons_top.constant <= 64) {
        self.cons_top.constant = 54;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        self.labelHeight.constant = 54;
    }else{
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//- (IBAction)infoBtn:(id)sender {
//    NSLog(@"1");
//}
//- (IBAction)contentBtn:(id)sender {
//    NSLog(@"2");
//}
@end
